package com.ronghui.cash.plugin;

import com.ronghui.cash.exception.*;
import com.ronghui.cash.vo.Response;
import org.apache.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;


@RestControllerAdvice
public class GlobalExceptionHandler {

	private static Logger logger = Logger.getLogger(GlobalExceptionHandler.class);

	/**
	 * 200 - Bad Request
	 */
	@ResponseStatus(HttpStatus.OK)
	@ExceptionHandler(BindException.class)
	public Response handleMethodArgumentNotValidException(BindException e) {
		BindingResult result = e.getBindingResult();
		FieldError error = result.getFieldError();
		// String field = error.getField();
		String code = error.getDefaultMessage();
		// String message = String.format("%s:%s", field, code);
		String message = String.format("%s", code);
        logger.debug("参数验证失败："+message);
		return new Response().failure(message);
	}

	/**
	 * 401 - Unauthorized
	 */
	@ResponseStatus(HttpStatus.UNAUTHORIZED)
	@ExceptionHandler(LoginException.class)
	public Response handleTokenException(LoginException e) {
		logger.debug("令牌验证失败");
		return new Response().failure("令牌验证失败");
	}

	/**
	 * 403
	 */

	@ResponseStatus(HttpStatus.FORBIDDEN)
	@ExceptionHandler(AuthException.class)
	public Response handleAuthIdentityException(AuthException e) {
		logger.debug("未完成认证");
		return new Response().failure("未完成认证");
	}
}